package org.stvd.repository.common.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.stvd.entities.common.AuditFlow;
import org.stvd.repository.base.impl.BaseDaoImpl;
import org.stvd.repository.common.AuditFlowDao;

/**
 * 审核记录Repository实现类
 * @author houzx
 */
@Repository("AuditFlowDao")
public class AuditFlowDaoImpl extends BaseDaoImpl<AuditFlow> implements AuditFlowDao{

    @Override
    public AuditFlow getAuditFlowByInfoId(String sourceTable, String sourceId) {
        String hql = "FROM AuditFlow WHERE sourceTable = ?0 AND sourceId = ?1";
        List<AuditFlow> list = findByHQL(hql, sourceTable, sourceId);
        if(list!=null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public List<Map<String, Object>> listAllAuditFlowDetail(String sourceTable, String sourceId) {
        String sql = " SELECT T1.* FROM audit_detail T1, "
                + " ( SELECT id FROM audit_flow WHERE source_table = :sourceTable AND source_id = :sourceId) T2"
            + " WHERE T1.flow_id = T2.id "
            + " ORDER BY T1.create_time DESC ";
        Map<String, Object> params = new HashMap<>();
        params.put("sourceTable", sourceTable);
        params.put("sourceId", sourceId);
        return findBySQLToMap(0, 0, sql, params);
    }

    @Override
    public List<Map<String, Object>> listUserAuditFlowDetail(String sourceTable, String sourceId, String auditorId) {
        String sql = " SELECT T1.* FROM audit_detail T1, "
                + " ( SELECT id FROM audit_flow WHERE source_table = :sourceTable AND source_id = :sourceId) T2"
            + " WHERE T1.flow_id = T2.id AND T1.auditor_id = :auditorId"
            + " ORDER BY T1.create_time DESC ";
        Map<String, Object> params = new HashMap<>();
        params.put("sourceTable", sourceTable);
        params.put("sourceId", sourceId);
        params.put("auditorId", auditorId);
        return findBySQLToMap(0, 0, sql, params);
    }

    @Override
    @Transactional
    public void deleteAuditFlowBySource(String sourceTable, String sourceId) {
        String sql = "DELETE FROM audit_flow WHERE source_table = :sourceTable AND source_id = :sourceId";
        em.createNativeQuery(sql)
            .setParameter("sourceTable", sourceTable)
            .setParameter("sourceId", sourceId)
            .executeUpdate();
        em.flush();
    }
}
